using FluentMigrator;

namespace AuthService.Infrastructure.Migrations;

/// <summary>
/// 简化用户表结构
/// 移除复杂的权限相关字段，只保留基础字段
/// </summary>
[Migration(20241217003)]
public class SimplifyUserTable : Migration
{
    public override void Up()
    {
        // 删除复杂的字段
        if (Schema.Table("Users").Column("TenantId").Exists())
            Delete.Column("TenantId").FromTable("Users");
        
        if (Schema.Table("Users").Column("Role").Exists())
            Delete.Column("Role").FromTable("Users");
        
        if (Schema.Table("Users").Column("Permissions").Exists())
            Delete.Column("Permissions").FromTable("Users");
        
        if (Schema.Table("Users").Column("LastLoginAt").Exists())
            Delete.Column("LastLoginAt").FromTable("Users");
        
        if (Schema.Table("Users").Column("LoginAttempts").Exists())
            Delete.Column("LoginAttempts").FromTable("Users");
        
        if (Schema.Table("Users").Column("LockedUntil").Exists())
            Delete.Column("LockedUntil").FromTable("Users");
        
        if (Schema.Table("Users").Column("EmailVerified").Exists())
            Delete.Column("EmailVerified").FromTable("Users");
        
        if (Schema.Table("Users").Column("EmailVerificationToken").Exists())
            Delete.Column("EmailVerificationToken").FromTable("Users");
        
        if (Schema.Table("Users").Column("PasswordResetToken").Exists())
            Delete.Column("PasswordResetToken").FromTable("Users");
        
        if (Schema.Table("Users").Column("PasswordResetExpires").Exists())
            Delete.Column("PasswordResetExpires").FromTable("Users");
        
        if (Schema.Table("Users").Column("RefreshToken").Exists())
            Delete.Column("RefreshToken").FromTable("Users");
        
        if (Schema.Table("Users").Column("RefreshTokenExpires").Exists())
            Delete.Column("RefreshTokenExpires").FromTable("Users");
        
        if (Schema.Table("Users").Column("Metadata").Exists())
            Delete.Column("Metadata").FromTable("Users");

        // 确保基础字段存在且正确
        if (!Schema.Table("Users").Column("DisplayName").Exists())
        {
            Alter.Table("Users")
                .AddColumn("DisplayName").AsString(100).Nullable();
        }
    }

    public override void Down()
    {
        // 回滚时重新添加字段（可选）
        Alter.Table("Users")
            .AddColumn("Role").AsString(50).WithDefaultValue("User")
            .AddColumn("LastLoginAt").AsDateTime().Nullable()
            .AddColumn("LoginAttempts").AsInt32().WithDefaultValue(0)
            .AddColumn("EmailVerified").AsBoolean().WithDefaultValue(false);
    }
}
